﻿angular.module('app')
    .service('topicCacheSrv', ['$cacheFactory', function($cacheFactory) {
            return $cacheFactory('topicsData');
        }
    ]);

angular.module('app')
    .service('replyCacheSrv', ['$cacheFactory', function ($cacheFactory) {
        return $cacheFactory('repliesData');
    }
    ]);

angular.module('app')
    .service('TopicSrv', ['$http', '$q', 'topicCacheSrv', 'replyCacheSrv', function ($http, $q, topicCacheSrv, replyCacheSrv) {
        var _topics = [];
        var _replies = [];

        _removeCache = function() {
            replyCacheSrv.removeAll();
            topicCacheSrv.removeAll();
        };

        return {
            topics: _topics,
            replies: _replies,
            removeCache: _removeCache,

            //api/topics?user=cgrant&query=&status=&pageSize=5&pageIndex=1&winthReplies=false
            getTopics: function (userName, query, status, pageSize, pageIndex, winthReplies) {
                var deferred = $q.defer();

                var start = new Date().getTime();
                
                var t = topicCacheSrv.get('topic-' + pageIndex);

                if (typeof t !== 'undefined') {
                    angular.copy(t, _topics);
                    deferred.resolve();
                } else {
                    $http({ method: 'GET', url: 'api/topics', params: { user: userName, query: query, status: status, pageSize: pageSize, pageIndex: pageIndex, winthReplies: winthReplies }})
                        .then(function (result) {
                            angular.copy(result.data, _topics);
                            // cache only the first 5 pages
                            if (pageIndex <= 5) {
                                topicCacheSrv.put('topic-' + pageIndex, result.data);
                            }
                            deferred.resolve();
                        },
                        function (error) {
                            deferred.reject();
                        });
                }

                //console.log('time taken for request (topics): ' + (new Date().getTime() - start) + 'ms');
                return deferred.promise;
            },
            //api/replies/1?user=cgrant&amp;showType=Recent/Old
            getTopicReplies: function (userName, toOid, showType) {
                var deferred = $q.defer();

                var start = new Date().getTime();

                var found = false;
                if (showType === 'Recent') {
                    var r = replyCacheSrv.get('replies');
                    if (typeof r !== 'undefined') {
                        angular.copy(r, _replies);
                        found = true;
                        deferred.resolve();
                    }
                }

                if (!found) {
                    $http({ method: 'GET', url: 'api/replies/' + toOid, params: { user: userName, showType: showType }})
                        .then(function (result) {
                            angular.copy(result.data, _replies);
                            if (showType === 'Recent') {
                                var info = replyCacheSrv.info();
                                if (info.size <= 5) {
                                    replyCacheSrv.put('replies-' + toOid, result.data);
                                }
                            }
                            deferred.resolve();
                        },
                        function (error) {
                            deferred.reject();
                        });
                }

                //console.log('time taken for request (replies): ' + (new Date().getTime() - start) + 'ms');
                return deferred.promise;
            },
            //api/topics?user=cgrant&amp;searchFor=aaa
            searchTopics: function (userName, query, timeout) {
                return $http({ method: 'GET', url: 'api/topics', params: { user: userName, searchFor: query }, cache: false, timeout: timeout });
            },
            //api/topics?user=cgrant&amp;topicId=1
            getTopicById: function (userName, topicId) {
                return $http({ method: 'GET', url: 'api/topics', params: { user: userName, topicId: topicId }, cache: false });
            },
            getTopicNewCount: function (userName) {
                return $http({ method: 'GET', url: 'api/topics', params: { user: userName }, cache: false, headers: { 'Abortable': false } });
            },
            addReply: function (params, dt) {
                _removeCache();

                return $http({
                    method: 'POST', url: 'api/topics', params: params, data: dt, cache: false, headers: { 'Content-Type': undefined },
                    transformRequest: function (data) {
                        if (typeof FormData != 'undefined') {
                            var fd = new FormData();
                            angular.forEach(data, function (value, key) {
                                if (key === 'filesList') {
                                    angular.forEach(value, function (value1, key1) {
                                        fd.append(key1, value1);
                                    });
                                }
                                fd.append(key, value);
                            });
                            return fd;
                        }
                    }
                });
            },
            addTopic: function (params, dt) {
                _removeCache();

                return $http({
                    method: 'POST', url: 'api/topics', params: params, data: dt, cache: false, headers: { 'Content-Type': undefined },
                    transformRequest: function (data) {
                        if (typeof FormData != 'undefined') {
                            var fd = new FormData();
                            angular.forEach(data, function (value, key) {
                                if (key === 'filesList') {
                                    angular.forEach(value, function (value1, key1) {
                                        fd.append(key1, value1);
                                    });
                                }
                                fd.append(key, value);
                            });
                            return fd;
                        }
                    }
                });
            },
            downloadAttachment: function (oid) {
                return $http({ method: 'GET', url: 'api/docs/' + oid, params: {}, cache: false });
            },
            uploadAttachment: function (from) {
                return $http({ method: 'POST', url: 'api/topics', params: { from: from }, cache: false });
            }
        };
    }
    ]);